﻿
#include "xnet_tiny.h"

// 交换16位，从大端法到小端法
uint16_t swap_order16(uint16_t v)
{
    return (((v & 0xff) << 8) | ((v >> 8) & 0xff));
}

// 交换32位，从大端法到小端法
uint32_t swap_order32(uint32_t v)
{
    uint32_t res=0;
    uint8_t *src=(uint8_t *)&v;
    uint8_t *dest=(uint8_t *)&res;
    dest[0]=src[3];
    dest[1]=src[2];
    dest[2]=src[1];
    dest[3]=src[0];
    return res;

}

xnet_packet_t *xnet_alloc_for_read(uint16_t data_size)
{
    // 声明读取的包，就是一个缓存数组
    rx_packet.data = rx_packet.payload; // 相当于把指针移到最后一位，把所有的数据清空
    rx_packet.size = data_size;
    return &rx_packet;
};

xnet_packet_t *xnet_alloc_for_send(uint16_t data_size)
{
    // 声明发送的包，也是缓存数组
    tx_packet.data = tx_packet.payload + XNET_CFG_PACKET_MAX_SIZE - data_size;
    tx_packet.size = data_size;
    return &tx_packet;
};

void add_header(xnet_packet_t *packet, uint16_t header_size)
{
    // 为包添加包头，将数据指针往前headersize位
    packet->size += header_size;
    packet->data -= header_size;
};
void remove_header(xnet_packet_t *packet, uint16_t header_size)
{
    // 为包删除包头
    packet->size -= header_size;
    packet->data += header_size;
};

void truncate_packet(xnet_packet_t *packet, uint16_t size)
{
    packet->size = min(packet->size, size);
}

int xnet_check_tmo(xnet_time_t *time, uint32_t sec)
{
    // 将当前时间与time对比，超过了sec时返回1，没超过返回0
    // 当sec<=0时，将time赋值为当前时间
    xnet_time_t curr = xsys_get_time();
    if (sec <= 0)
    {
        *time = curr;
        return 0;
    }
    else if ((curr - *time) >= (sec))
    {
        *time = curr;
        return 1;
    }
    return 0;
};

// 判断目标ip和我自己的ip是否相等，缓冲区
int xipaddr_is_equal_buf(xipaddr_t myip, uint8_t *target)
{
    return !memcmp((myip.array), target, XNET_IPV4_ADDR_SIZE);
}
// 判断目标ip和我自己的ip是否相等，32位数字
int xipaddr_is_equal(xipaddr_t myip, uint32_t target)
{
    return myip.addr == target;
}